<template>
  <div class="login-container">
    <div class="login-box">
      <h1 class="title">AI Agent 聚合平台</h1>
      <p class="subtitle">发现与使用适合你的智能体</p>
      
      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 登录 -->
        <el-tab-pane label="登录" name="login">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="phone">
              <el-input
                v-model="loginForm.phone"
                placeholder="请输入手机号"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="code" v-if="loginType === 'code'">
              <div class="code-input">
                <el-input
                  v-model="loginForm.code"
                  placeholder="请输入验证码"
                  size="large"
                />
                <el-button
                  :disabled="countdown > 0"
                  @click="handleSendCode('login')"
                  size="large"
                >
                  {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item prop="password" v-if="loginType === 'password'">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
              />
            </el-form-item>
            
            <div class="login-type-switch">
              <el-link
                type="primary"
                @click="loginType = loginType === 'code' ? 'password' : 'code'"
              >
                {{ loginType === 'code' ? '密码登录' : '验证码登录' }}
              </el-link>
            </div>
            
            <el-button
              type="primary"
              size="large"
              class="submit-btn"
              @click="handleLogin"
              :loading="loading"
            >
              登录
            </el-button>
          </el-form>
        </el-tab-pane>
        
        <!-- 注册 -->
        <el-tab-pane label="注册" name="register">
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="code">
              <div class="code-input">
                <el-input
                  v-model="registerForm.code"
                  placeholder="请输入验证码"
                  size="large"
                />
                <el-button
                  :disabled="countdown > 0"
                  @click="handleSendCode('register')"
                  size="large"
                >
                  {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item prop="nickname">
              <el-input
                v-model="registerForm.nickname"
                placeholder="请输入昵称（可选）"
                size="large"
              />
            </el-form-item>
            
            <el-button
              type="primary"
              size="large"
              class="submit-btn"
              @click="handleRegister"
              :loading="loading"
            >
              注册
            </el-button>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { sendCode, register, loginWithCode, loginWithPassword } from '@/api/auth'
import { getUserInfo } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

const activeTab = ref('login')
const loginType = ref('code')
const loading = ref(false)
const countdown = ref(0)

const loginForm = reactive({
  phone: '',
  code: '',
  password: ''
})

const registerForm = reactive({
  phone: '',
  code: '',
  nickname: ''
})

const loginRules = {
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const registerRules = {
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 发送验证码
const handleSendCode = async (purpose) => {
  const phone = purpose === 'login' ? loginForm.phone : registerForm.phone
  
  if (!phone) {
    ElMessage.warning('请输入手机号')
    return
  }
  
  try {
    await sendCode(phone, purpose)
    ElMessage.success('验证码已发送')
    
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error(error)
  }
}

// 登录
const handleLogin = async () => {
  try {
    loading.value = true
    
    let res
    if (loginType.value === 'code') {
      res = await loginWithCode(loginForm.phone, loginForm.code)
    } else {
      res = await loginWithPassword(loginForm.phone, loginForm.password)
    }
    
    userStore.setToken(res.data.access_token)
    
    // 获取用户信息
    const userRes = await getUserInfo()
    userStore.setUserInfo(userRes.data)
    
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 注册
const handleRegister = async () => {
  try {
    loading.value = true
    
    const res = await register(
      registerForm.phone,
      registerForm.code,
      registerForm.nickname
    )
    
    userStore.setToken(res.data.access_token)
    
    // 获取用户信息
    const userRes = await getUserInfo()
    userStore.setUserInfo(userRes.data)
    
    ElMessage.success('注册成功，随机密码已发送至手机')
    router.push('/')
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 420px;
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 24px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 8px;
  color: #2a5085;
}

.subtitle {
  text-align: center;
  color: #64748b;
  margin-bottom: 32px;
  font-size: 14px;
}

.login-tabs {
  margin-top: 20px;
}

.code-input {
  display: flex;
  gap: 12px;
}

.code-input .el-input {
  flex: 1;
}

.login-type-switch {
  text-align: right;
  margin-bottom: 24px;
}

.submit-btn {
  width: 100%;
  margin-top: 8px;
}
</style>

